package com.sinping.qh.api.support;

import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * @author wupeng
 * @create 2018/5/30
 */
public class ResDtoUtil {


    public static ResDtoUtil defaultUtil() {
        return new ResDtoUtil();
    }

    /**
     * 分页查询对象转换
     * @param resDto 返回信息
     * @param datas 分页数据
     * @param targetClass 目标类
     * @param frontPage FrontPage
     */
    public void pageDomainDtoToFrontDto(ResDto resDto, Page datas, Class targetClass, FrontPage frontPage) {
        List apiOrders = BeanMapper.mapList(datas.getContent(), targetClass);
        long totalPages = datas.getTotalPages();
        int currentPage = frontPage.getPage();
        frontPage = new FrontPage();
        frontPage.setPage(currentPage);
        frontPage.setTotal((int) datas.getTotalElements());
        frontPage.setPages((int) totalPages);
        frontPage.setRecords(apiOrders);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(frontPage));
    }

    /**
     * 返回 frontpage
     * @param datas
     * @param targetClass
     * @param frontPage
     */
    public FrontPage pageDomainDtoToFrontDto(Page datas, Class targetClass, FrontPage frontPage) {
        List apiOrders = BeanMapper.mapList(datas.getContent(), targetClass);
        long totalPages = datas.getTotalPages();
        frontPage.setTotal((int) datas.getTotalElements());
        frontPage.setPages((int) totalPages);
        frontPage.setRecords(apiOrders);
        return frontPage;
    }

    /**
     * list查询对象转换
     * @param resDto 返回信息
     * @param datas list 数据
     * @param targetClass 目标类
     * @param frontPage FrontPage
     */
    public void listDomainDtoToFrontDto(ResDto resDto, List datas, Class targetClass, FrontPage frontPage) {
        List apiOrders = BeanMapper.mapList(datas, targetClass);
        int currentPage = frontPage.getPage();
        frontPage = new FrontPage();
        frontPage.setPage(currentPage);
        frontPage.setRecords(apiOrders);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(frontPage));
    }
}
